from demo.init import db
from datetime import datetime

'''
简单关系实例
'''
# 通过db.backref()函数来为反向引用定义lazy状态
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    pub_date = db.Column(db.DateTime)

    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    # 第一个参数是正向引用，Post引用Category,第二个参数是反向引用，Category引用Post
    category = db.relationship('Category',
                               backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, body, category, pub_date=None):
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date
        self.category = category

    def __repr__(self):
        return '<Post %r>' % self.title

class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Category %r>' % self.name

# 创建所有表
db.create_all()

# 删除Post表和Category表中的所有行
Post.query.delete()
Category.query.delete()

# 添加Category和Post的数据，
category1 = Category('IT')
post1 = Post('Hello Python!', 'Python is pretty cool', category1)
post2 = Post('Hello Java!', 'Java is pretty cool', category1)

db.session.add(category1)
db.session.add(post1)
db.session.commit()

print('category1的posts:', category1.posts)

# 查询与category1相关的所有post文章
posts = category1.posts.all()

print('category1相关的post:', posts)